const fs = require('fs');
const path = require('path');

// 导入自动绑卡函数
const { autoBindCard } = require('./auto-bind-card');

// 创建日志文件
const logFile = path.join(__dirname, 'bind_card_log.txt');
const logStream = fs.createWriteStream(logFile, { flags: 'a' });

// 重写 console.log 和 console.error
const originalLog = console.log;
const originalError = console.error;

console.log = function(...args) {
    const message = `[${new Date().toLocaleString()}] ${args.join(' ')}\n`;
    logStream.write(message);
    originalLog.apply(console, args);
};

console.error = function(...args) {
    const message = `[${new Date().toLocaleString()}] ERROR: ${args.join(' ')}\n`;
    logStream.write(message);
    originalError.apply(console, args);
};

// 读取卡片数据文件
const cardData = fs.readFileSync(path.join(__dirname, 'live_108.txt'), 'utf8');

// 解析卡片数据
const cards = cardData
    .split('\n')
    .map(line => {
        // 移除空白字符并分割
        const parts = line.trim().split('|');
        
        // 验证数据格式
        if (parts.length !== 4) {
            console.error(`无效的数据格式: ${line}`);
            return null;
        }

        const [cardNumber, expMonth, expYear, cvc] = parts.map(part => part.trim());
        console.log(cardNumber, expMonth, expYear, cvc);
        
        // 验证卡号长度
        if (cardNumber.length !== 16) {
            console.error(`无效的卡号长度: ${cardNumber}`);
            return null;
        }

        // 验证月份
        const month = parseInt(expMonth);
        if (isNaN(month) || month < 1 || month > 12) {
            console.error(`无效的月份: ${expMonth}`);
            return null;
        }

        // 验证年份
        const year = parseInt(expYear);
        if (isNaN(year) || year < 24) {
            console.error(`无效的年份: ${expYear}`);
            return null;
        }

        // 验证安全码
        if (cvc.length !== 3) {
            console.error(`无效的安全码长度: ${cvc}`);
            return null;
        }

        return {
            cardNumber,
            expMonth: month.toString().padStart(2, '0'), // 确保月份是两位数
            expYear: year.toString(),
            cvc,
            zipCode: '76105' // 使用默认邮编
        };
    })
    .filter(card => card !== null); // 过滤掉无效的数据

console.log(`成功解析 ${cards.length} 张有效卡片`);

// 创建结果文件
const successFile = path.join(__dirname, 'success_cards.txt');
const failFile = path.join(__dirname, 'fail_cards.txt');

// 清空或创建结果文件
fs.writeFileSync(successFile, '');
fs.writeFileSync(failFile, '');

// 批量处理函数
async function processCards() {
    console.log(`开始批量处理 ${cards.length} 张卡片...`);
    
    for (let i = 0; i < cards.length; i++) {
        const card = cards[i];
        console.log(`正在处理第 ${i + 1}/${cards.length} 张卡片: ${card.cardNumber}`);
        
        try {
            const result = await autoBindCard(card);
            
            // 记录结果
            const resultLine = `${card.cardNumber}|${card.expMonth}|${card.expYear}|${card.cvc}|${new Date().toLocaleString()}\n`;
            
            if (result.bindResult && result.bindResult.success) {
                fs.appendFileSync(successFile, resultLine);
                console.log(`卡片 ${card.cardNumber} 处理成功`);
            } else {
                fs.appendFileSync(failFile, resultLine);
                console.log(`卡片 ${card.cardNumber} 处理失败`);
            }
            
            // 添加延迟，避免请求过于频繁
            await new Promise(resolve => setTimeout(resolve, 2000));
            
        } catch (error) {
            console.error(`处理卡片 ${card.cardNumber} 时发生错误:`, error);
            const errorLine = `${card.cardNumber}|${card.expMonth}|${card.expYear}|${card.cvc}|${new Date().toLocaleString()}|${error.message}\n`;
            fs.appendFileSync(failFile, errorLine);
        }
    }
    
    console.log(`批量处理完成！`);
    console.log(`成功卡片已保存到: ${successFile}`);
    console.log(`失败卡片已保存到: ${failFile}`);
    console.log(`日志已保存到: ${logFile}`);
    
    // 关闭日志流
    logStream.end();
}

// 执行批量处理
processCards().catch(error => {
    console.error(`批量处理过程中发生错误:`, error);
    logStream.end();
}); 